package me.siphone.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.hjq.http.EasyHttp;
import com.hjq.http.config.IRequestApi;
import com.hjq.http.listener.HttpCallbackProxy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import me.siphone.Constants;
import me.siphone.adapter.TemplateAdapter;
import me.siphone.http.api.QueryModelApi;
import me.siphone.http.api.SendSmsApi;
import me.siphone.http.model.HttpData;
import me.siphone.view.grouptree.Device;
import me.siphone.view.grouptree.GroupTreeFragment;
import org.linphone.R;

public class TemplateCallFragment extends BaseFragment {
    private Button btnCall;
    private RecyclerView rvTemplate;
    private QueryModelApi.Model selectedModel;

    @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_template_call, container, false);

        btnCall = view.findViewById(R.id.btn_call);
        rvTemplate = view.findViewById(R.id.rv_template);
        rvTemplate.setLayoutManager(new LinearLayoutManager(getContext()));
        rvTemplate.setItemAnimator(null);

        EasyHttp.get(this)
                .api(new QueryModelApi())
                .request(
                        new HttpCallbackProxy<Map<String, List<QueryModelApi.Model>>>(this) {
                            @Override
                            public void onHttpSuccess(
                                    @NonNull Map<String, List<QueryModelApi.Model>> result) {
                                super.onHttpSuccess(result);
                                List<QueryModelApi.Model> modelList = new ArrayList<>();
                                for (List<QueryModelApi.Model> models : result.values()) {
                                    modelList.addAll(models);
                                }

                                Collections.sort(
                                        modelList,
                                        new Comparator<QueryModelApi.Model>() {
                                            @Override
                                            public int compare(
                                                    QueryModelApi.Model model,
                                                    QueryModelApi.Model t1) {
                                                return t1.getGrade() - model.getGrade();
                                            }
                                        });

                                if (!modelList.isEmpty()) {
                                    modelList.get(0).setSelected(true);
                                    selectedModel = modelList.get(0);
                                }
                                Log.d("sisyphus", "model====>" + new Gson().toJson(modelList));
                                TemplateAdapter templateAdapter = new TemplateAdapter(modelList);
                                templateAdapter.setOnItemSelectedListener(
                                        new TemplateAdapter.OnItemSelectedListener() {
                                            @Override
                                            public void onItemSelected(QueryModelApi.Model model) {
                                                selectedModel = model;
                                            }
                                        });
                                rvTemplate.setAdapter(templateAdapter);
                            }
                        });

        btnCall.setOnClickListener(
                v -> {
                    btnCall.setClickable(false);
                    if (getFragmentManager() != null) {
                        GroupTreeFragment fragment =
                                (GroupTreeFragment)
                                        getChildFragmentManager()
                                                .findFragmentById(R.id.group_tree_fragment);
                        List<Device> selectedDevices = fragment.getSelectedDeviceList();
                        Log.d("sisyphus", "选中设备：" + selectedDevices);
                        startCall(selectedDevices);
                    } else {
                        btnCall.setClickable(true);
                    }
                });

        return view;
    }

    public void startCall(List<Device> deviceList) {
        if (deviceList.isEmpty()) {
            Toast.makeText(getContext(), "请至少选择一个设备", Toast.LENGTH_SHORT).show();
            btnCall.setClickable(true);
            return;
        }

        if (selectedModel == null) {
            Toast.makeText(getContext(), "请先选择一个模版", Toast.LENGTH_SHORT).show();
            btnCall.setClickable(true);
            return;
        }

        ArrayList<String> numbers = new ArrayList<>();
        for (Device device : deviceList) {
            numbers.add(device.number);
        }

        EasyHttp.post(this)
                .api(new SendSmsApi(numbers, selectedModel.getId(), 1))
                .request(
                        new HttpCallbackProxy<HttpData<List<String>>>(this) {
                            @Override
                            public void onHttpSuccess(@NonNull HttpData<List<String>> result) {
                                super.onHttpSuccess(result);
                                if (result.getCode() == 200) {
                                    if (getFragmentManager() != null) {
                                        GroupTreeFragment fragment =
                                                (GroupTreeFragment)
                                                        getChildFragmentManager()
                                                                .findFragmentById(
                                                                        R.id.group_tree_fragment);
                                        fragment.clearSelected();

                                        AnswerFragment answerFragment = new AnswerFragment();
                                        Bundle data = new Bundle();
                                        data.putInt(Constants.CALL_TYPE, 0);
                                        data.putString(Constants.CALL_ID, result.getMsg());
                                        data.putString(
                                                Constants.CALL_CONTENT, selectedModel.getRemark());
                                        data.putStringArrayList(Constants.CALL_DEVICE_IDS, numbers);
                                        answerFragment.setArguments(data);

                                        getFragmentManager()
                                                .beginTransaction()
                                                .add(R.id.fl_call_container, answerFragment)
                                                .addToBackStack(
                                                        answerFragment.getClass().getSimpleName())
                                                .commit();
                                    }
                                }
                            }

                            @Override
                            public void onHttpEnd(@NonNull IRequestApi api) {
                                super.onHttpEnd(api);
                                btnCall.setClickable(true);
                            }
                        });
    }
}
